import React, { Component } from 'react'
import {
  Form,
  Input,
  Radio,
  InputNumber,
  Button,
  message,
  Spin,
} from 'antd'
import request from '@/Utils/fecth'
import Title from '@/components/Title'
import _ from 'lodash'
import { address } from '@/Utils/apiConfig'
import { inject } from 'mobx-react/index'
import AuthComponent from '@/components/AuthComponent'

import './index.less'

// import { orgObj } from '@/Utils/CONST'
import regexp from '@/Utils/regexp'

const { addOrg } = address.fabric
const { checkDomain } = address.common

@AuthComponent('fabric-org-create')
@inject('SocketModel')
class CreateOrgation extends Component {
  constructor(props) {
    super(props)
    this.state = {
      mode: 'out',
      type: 'orderer',
      caList: [],
      peerList: [],
      org_expiration: 1,
      // 初始值
      initialValues: {
        org_name: '',
        org_domain: '',
        org_type: 'orderer',
        org_region: 'cn-huhehaote',
        node_num: '',
        performance: 'STANDARD',
        org_expiration: 1,
        org_description: '',
        isGuomi: 0,
        version: '1.4.6',
      },
      // 右边当前选中值
      currentValues: {
        org_name: '',
        org_domain: '',
        org_type: 'Orderer',
        org_region: '呼和浩特',
        node_num: '',
        performance: 'STANDARD',
        org_expiration: 1,
        total_price: '',
        isGuomi: 0,
        version: '1.4.6',
      },
      loading: false,
      checkPeerFlag: 'false',
    }
    this.caList = []
    this.peerList = []
  }
  formRef = React.createRef();

  // 表单真实的数据提交
  // 构建组织-云节点模式提交
  onFinish = async(values) => {
    this.setState({
      loading: true,
    })
    let messageError = {
      409: '此域名已使用！',
      408: '组织名称已存在',
    }
    const options = {
      ...values,
      run_mode: 'cloud',
      isGuomi: !!values.isGuomi,
    }
    let res = await request().post(addOrg, options)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('组织创建中...')
      this.props.history.goBack()
    } else {
      message.error(_.get(messageError, _.get(res, 'status')) || _.get(res, 'error') || '创建组织失败')
    }
  };

  onChange = (values) => {
    let currentValues = {
      ...this.state.currentValues,
      ...values,
    }
    this.setState({
      currentValues,
    })
  };
  submit = () => {
    this.formRef.current.submit()
  };

  // 构建组织-外部节点模式提交
  createOrg = async(values) => {
    const { checkPeerFlag } = this.state
    if (checkPeerFlag !== 'true') { message.warn('请填写正确的节点信息'); return false }
    const caArrs = this.state.caList.map((element) => {
      return {
        name: element.name,
        ip: element.host,
        user: element.username,
        _pwd: element._pwd,
        type: 'ca',
      }
    })
    const peerArrs = this.state.peerList.map((element) => {
      return {
        name: element.name,
        ip: element.host,
        user: element.username,
        _pwd: element._pwd,
        type: values.org_type,
      }
    })
    // 上传的参数
    const options = {
      org_name: values.org_name,
      org_domain: values.org_domain,
      org_type: values.org_type,
      org_description: values.org_description,
      run_mode: 'bare',
      nodes: caArrs.concat(peerArrs),
    }

    let res = await request().post(addOrg, options)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('创建组织成功!')
      this.props.history.goBack()
    } else {
      message.error('创建组织失败')
    }
  };

  render() {
    const { initialValues, loading,
    } = this.state
   
    return (
      <div className="common fabric-create-org">
        <Spin spinning={loading}>
          {/* <TabsList> */}
          {/* <div className="tabs-wrapper">
              <Title title="填写配置" />
              <div>
                <Form
                  className="create-form"
                  labelAlign="left"
                  initialValues={initialValues}
                  onFinish={this.createOrg}
                  onValuesChange={(changedValues, allValues) =>
                    this.onChange(changedValues)
                  }
                  onChange={() => this.forceUpdate()}
                  ref={(ref) => (this.form = ref)}
                >
                  <Form.Item
                    name="org_name"
                    label="组织名称"
                    className="form-item"
                    help="请输入组织名称，最多输入20字符"
                    rules={[
                      { required: true, message: "请输入组织名称" },
                      //   () => ({
                      //     validator(rule, value) {
                      //         let r = /^[^\u4e00-\u9fa5]+$/
                      //         if (value) {
                      //             if (!r.test(value)) {
                      //                 return Promise.reject('组织名称不能包含中文！');
                      //             } else {
                      //                 return Promise.resolve();
                      //             }
                      //         } else {
                      //             return Promise.resolve();
                      //         }
                      //     },
                      // })
                    ]}
                  >
                    <Input
                      placeholder="请输入"
                      className="input"
                      maxLength={20}
                      autoComplete="off"
                    />
                  </Form.Item>
                  <Form.Item
                    name="org_domain"
                    label="组织域名"
                    className="form-item"
                    help="请填写正确的组织域名，最多输入32个字符"
                    rules={[
                      { required: true, message: "请输入组织域名" },
                      ({ getFieldValue }) => ({
                        validator(rule, value) {
                          if (value) {
                            if (!regexp.url.test(value)) {
                              return Promise.reject("请输入正确的域名");
                            }
                            if (/[_]/g.test(value)) {
                              return Promise.reject("请输入正确的域名");
                            }
                            return Promise.resolve();
                          } else {
                            return Promise.resolve();
                          }
                        },
                      }),
                    ]}
                  >
                    <Input
                      placeholder="请输入"
                      className="input"
                      autoComplete="off"
                      maxLength={32}
                    />
                  </Form.Item>
                  <Form.Item className="form-item" label="组织类型" name="org_type">
                    <Radio.Group >
                      <Radio.Button value="orderer">Orderer</Radio.Button>
                      <Radio.Button value="peer">Peer</Radio.Button>
                    </Radio.Group>

                  </Form.Item>

                  <Form.Item
                    name="org_description"
                    label="描述"
                    className="form-item"
                  >
                    <Input.TextArea
                      placeholder="请输入描述，最多输入250字符"
                      maxLength={250}
                    />
                  </Form.Item>
                  <div className="diver" />
                  <Form.Item className="form-item-required" label={<div className="common-select">CA节点</div>} >
                    <Peer
                      form={this.form}
                      flag="caList"
                      isShowDelete={false}
                      getForm={() => {
                        return this.form;
                      }}
                      chengeCheck={(status) => {
                        this.setState({
                          checkPeerFlag: status
                        })
                      }}
                      status={checkPeerFlag}
                      onChange={(key, list) => {
                        this.setState({
                          [key]: list,
                        });
                      }}
                    />
                  </Form.Item>
                  <Form.Item
                    // label="Peer/Orderer节点："
                    label={`${currentValues.org_type}节点：`}
                    style={{ textTransform: "capitalize" }}
                  >
                    <Peer
                      form={this.form}
                      flag="peerList"
                      status={checkPeerFlag}
                      getForm={() => {
                        return this.form;
                      }}
                      chengeCheck={(status) => {
                        this.setState({
                          checkPeerFlag: status
                        })
                      }}
                      onChange={(key, list) => {
                        this.setState({
                          [key]: list,
                        });
                      }}
                    />
                  </Form.Item>
                  <Form.Item>
                    <div className="peer-check">
                      * 节点信息填写完成后，点击右侧按钮，进行节点检测
                        <Button className="com-btn-primary com-small-btn" disabled={checkPeerFlag === "checking"} type="primary" onClick={() => { this.peerCheckFn() }}>节点检测</Button>
                    </div>
                  </Form.Item>

                  <Form.Item>
                    <Button className="com-btn-primary com-normal-btn submit" htmlType="submit">
                      提&nbsp;交
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div> */}
          <div style={{ display: 'flex', alignItems: 'flex-start' }}>
            <div className="tabs-wrapper">
              <Title title="填写配置" />
              <Form
                className="create-form bare-form "
                labelAlign="left"
                ref={this.formRef}
                onValuesChange={(changedValues) =>
                  this.onChange(changedValues)
                }
                initialValues={initialValues}
                onFinish={this.onFinish}
              >
                <Form.Item
                  name="version"
                  label="版本"
                  className="form-item"
                  // help="* 2.2.1不支持国密算法"
                >
                  <Radio.Group>
                    <Radio.Button value="1.4.6">1.4.6</Radio.Button>
                    {/* <Radio.Button disabled={currentValues.isGuomi === 1} value="2.2.1">2.2.1</Radio.Button> */}
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  name="org_name"
                  label="组织名称"
                  className="form-item"
                  help="请输入组织名称，最多输入20字符"
                  rules={[
                    { required: true, message: '请输入组织名称！' },
                  ]}
                >
                  <Input
                    placeholder="请输入组织名称"
                    className="input"
                    maxLength={20}
                    style={{ width: '320px' }}
                  />
                </Form.Item>
                <Form.Item
                  name="org_domain"
                  label="组织域名"
                  className="form-item"
                  validateFirst
                  validateTrigger="onBlur"
                  rules={[
                    { required: true, message: '请输入组织域名' },
                    () => ({
                      validator(rule, value = '') {
                        if (!regexp.url.test(value) || /[_A-Z]/g.test(value)) {
                          return Promise.reject('请输入正确的域名')
                        }
                        return Promise.resolve()
                      },
                    }),
                    {
                      validator: (_, value) => {
                        return new Promise(async(resolve, reject) => {
                          const { status, data = {}} = await request().get(checkDomain.format({ domain: value }))
                          if (status === 200 && data.exist) {
                            reject('该域名已被使用')
                          } else {
                            resolve()
                          }
                        })
                      },
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入组织域名，最多输入32个字符"
                    className="input"
                    maxLength={32}
                    style={{ width: '320px' }}
                  />
                </Form.Item>
                <Form.Item
                  name="org_type"
                  label="组织类型"
                  className="form-item"
                >
                  <Radio.Group>
                    <Radio.Button value="orderer">Orderer</Radio.Button>
                    <Radio.Button value="peer">Peer</Radio.Button>
                  </Radio.Group>
                </Form.Item>
                {/* <Form.Item
                  name="org_region"
                  label="地域"
                  className="form-item"
                >
                  <Radio.Group>
                    <Radio.Button value="cn-huhehaote">呼和浩特</Radio.Button>
                  </Radio.Group>
                </Form.Item> */}
                <Form.Item
                  name="isGuomi"
                  label="国密算法"
                >
                  {/* 只有企业版支持国密 */}
                  <Radio.Group>
                    {/* <Radio disabled={currentValues.performance === 'STANDARD' || currentValues.version === '2.2.1'} value={1}>是</Radio> */}
                    <Radio value={1}>是</Radio>
                    <Radio value={0}>否</Radio>
                  </Radio.Group>
                </Form.Item>
                <div className="diver"></div>
                <Form.Item
                  name="node_num"
                  label="节点数量"
                  className="form-item"
                  rules={[
                    {
                      required: true,
                      message: '请输入节点数量',
                    },
                  ]}
                >
                  <InputNumber min={1} max={1000} autoComplete="off" parser={value => value.replace(/\$\s?|(,*)(\.*)/g, '')} />
                </Form.Item>

                {/* <Form.Item
                  name="performance"
                  label="节点规格"
                  className="form-item"
                  help="* 标准版不支持国密算法"
                >
                  <Radio.Group>
                    <Radio.Button disabled={currentValues.isGuomi === 1} value="STANDARD">标准版</Radio.Button>
                    <Radio.Button value="ENTERPRISE">企业版</Radio.Button>
                  </Radio.Group>
                </Form.Item> */}
                <Form.Item
                  name="org_description"
                  label="描述"
                  className="form-item"
                >
                  <Input.TextArea
                    placeholder="请输入描述，最多输入250字符"
                    className="description"
                    maxLength={250}
                    autoComplete="off"
                  />
                </Form.Item>
                {/* <Form.Item
                  name="org_expiration"
                  label="购买时长"
                  className="form-item three-radio"
                >
                  <div className="radio-group">
                    <div className={this.state.org_expiration === 1 ? 'view view-select' : 'view'}
                      onClick={() => {
                        this.setState({ org_expiration: 1 })
                        this.formRef.current.setFieldsValue({ org_expiration: 1 })
                        this.onChange({ org_expiration: 1 })
                      }}>一个月</div>
                    <div className={this.state.org_expiration === 6 ? 'view view-select' : 'view'}
                      onClick={() => {
                        this.setState({ org_expiration: 6 })
                        this.formRef.current.setFieldsValue({ org_expiration: 6 })
                        this.onChange({ org_expiration: 6 })
                      }}>半年</div>
                    <div className={this.state.org_expiration === 12 ? 'view view-select' : 'view'}
                      onClick={() => {
                        this.setState({ org_expiration: 12 })
                        this.formRef.current.setFieldsValue({ org_expiration: 12 })
                        this.onChange({ org_expiration: 12 })
                      }}>一年</div>
                  </div>
                </Form.Item> */}
                <Form.Item className="form-item" label=" ">
                  <Button type="primary" onClick={this.submit}>确认</Button>
                  <Button style={{ marginLeft: '12px' }} onClick={() => this.props.history.goBack()}>取消</Button>
                </Form.Item>
              </Form>
            </div>

            {/* <div className="org-current-info current-info">
              <Title title="当前配置" />
              <div className="info">
                <div className="item-info">
                  <span className="item-text">组织名称</span>
                  <span className="item-value">
                    {currentValues.org_name || "-"}
                  </span>
                </div>
                <div className="item-info">
                  <span className="item-text">组织域名</span>
                  <span className="item-value">
                    {currentValues.org_domain || "-"}
                  </span>
                </div>
                <div className="item-info">
                  <span className="item-text">组织类型</span>
                  <span
                    className="item-value"
                    style={{ textTransform: "capitalize" }}
                  >
                    {currentValues.org_type}
                  </span>
                </div>
                <div className="item-info">
                  <span className="item-text">地域</span>
                  <span className="item-value">
                    {currentValues.org_region}
                  </span>
                </div>
                <div className="item-info">
                  <span className="item-text">支持国密算法</span>
                  <span className="item-value">
                    {currentValues.isGuomi ? '支持' : '不支持'}
                  </span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">节点数量</span>
                  <span className="item-value">
                    {Number(currentValues.node_num) || "-"}
                  </span>
                </div>
                <div className="item-info">
                  <span className="item-text">节点规格</span>
                  <span className="item-value">
                    {orgObj.performance[currentValues.performance]}
                  </span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">购买时长</span>
                  <span className="item-value">
                    {_.get(org_expiration, currentValues.org_expiration)}
                  </span>
                </div>
                <div className="diver"></div>
                <div className="item-info">
                  <span className="item-text">配置费用</span>
                  <span className="item-value">
                    <span className="symbol">¥</span>11988.00
                  </span>
                </div>
              </div>
              <div className="btn">
                <Button
                  className="buy-btn com-btn-primary"
                  onClick={() => this.submit()}
                  type="submit"
                >
                  立即购买
                </Button>
              </div>
            </div> */}
          </div>
          {/* </TabsList> */}
        </Spin>
      </div>
    )
  }
}
export default CreateOrgation
